package edu.lingnan.rili.utils;

import com.alibaba.excel.EasyExcel;
import edu.lingnan.rili.vo.MarksVo;
import org.apache.http.HttpResponse;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author xBaozi
 * @version 1.0
 * @classname DownloadUtils
 * @description Excel文件导出工具类
 * @date 2022/3/22 21:42
 */
public class DownloadUtils {
    /**
     * @description 利用EasyExcel导出Excel文件
     * @author xBaozi
     * @date 21:52 2022/3/22
     * @param response      响应体
     * @param fileName      文件名
     * @param list          文件数据
     * @param objectClass   需要导出类的字节码
     **/
    public static <T> void download(HttpServletResponse response, String fileName, List<T> list, Class<T> objectClass) throws IOException {
        //设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //设置防止文件名中文乱码
        fileName = URLEncoder.encode(fileName, "utf-8");
        // Content-disposition:attachment本次操作为下载
        // Content-disposition:inline本次操作为在线打开
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 将集合写入到excel中
        EasyExcel.write(response.getOutputStream(), objectClass).sheet().doWrite(list);
    }
}
